# -*- coding=utf8 -*-
import tornado.httpserver
import os
import datetime
import time
import json
import tornado.ioloop
import tornado.options
import tornado.web
from models.Item import Item, Session
import base64


class InsertItemHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', friendly user!')

    def post(self):
        ItemO = json.loads(self.request.body)
        attr = ItemO['attr'].replace(' ', ',')
        attr = attr.replace('，', ',')
        attr = attr.replace('.', ',')
        attr = attr.replace('。', ',')
        attr = attr.replace('-', ',')
        attr = attr.replace('—', ',')
        ItemO['attr'] = attr
        session = Session()
        c = session.query(Item).filter_by(name=ItemO['name'], position=ItemO['pos'], attr=ItemO['attr'],
                                          price=ItemO['price'], pic=ItemO['image_data']).count()
        if c != 0:
            ret = {'code': 1, 'desc': '已经存在'}
            self.write(json.dumps(ret))
            return
        img = ItemO['image_data']
        timestamp = datetime.datetime.now()
        fileName = (str(timestamp) + '.jpg').replace(':', '_')
        dirname = 'data/imgfiles'
        fileName = dirname + '/' + fileName
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        if img != '':
            d = img.split(',')[1]
            filecontent = None
            filecontent = base64.b64decode(d)
            
            # 写入图片数据到本地文件
            # with open(fileName, "ab") as f:
            #     f.write(filecontent)
        item = Item(name=ItemO['name'], position=ItemO['pos'], attr=ItemO['attr'], pic=ItemO['image_data'],
                    picFileName=fileName,
                    price=ItemO['price'], created_date=timestamp, update_date=timestamp)

        session.add(item)
        session.commit()
        ret = {'code': 0, 'desc': '保存成功'}
        self.write(json.dumps(ret))
        pass
